package com.longnuoqi.mydoctor.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.adapter.NewsRelateListAdapter;
import com.longnuoqi.mydoctor.entity.News;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.longnuoqi.mydoctor.utils.OtherUtil;
import com.longnuoqi.mydoctor.utils.VolleyUtil;
import com.longnuoqi.mydoctor.widget.MyListView;
import com.yunhe.mydoctor.R;

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2015/12/26.
 */
public class NewsContentActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;
    private boolean isLogin = false;
    private String access_token;
    private static final String TYPE = "info";
    private String titleStr;

    private int id;
    private String url;
    private String name;

    private ImageView back;
    private ImageView favorite;
    private ImageView share;

    private TextView title;
    private TextView time;
    private TextView from;
    private TextView message;
    private TextView keywords;

    private MyListView listView;
    private NewsRelateListAdapter adapter;

    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(NewsContentActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_item_layout);
        ActivityCollection.addActivity(this);
        OtherUtil.showProgress(this, "", "正在加载内容……", 6000);
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        url = "http://www.tngou.net/api/info/show?id=" + id;
        name = "news_item_" + id + ".txt";
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        isLogin = sharedPreferences.getBoolean("islogin", false);
        init();
        getData();
    }

    private void init() {
        back = (ImageView) findViewById(R.id.news_back_btn);
        favorite = (ImageView) findViewById(R.id.news_favorite_btn);
        share = (ImageView) findViewById(R.id.news_share_btn);

        back.setOnClickListener(onClickListener);
        favorite.setOnClickListener(onClickListener);
        share.setOnClickListener(onClickListener);

        title = (TextView) findViewById(R.id.news_content_title);
        time = (TextView) findViewById(R.id.news_content_time);
        from = (TextView) findViewById(R.id.news_content_from);
        message = (TextView) findViewById(R.id.news_content_message);
        keywords = (TextView) findViewById(R.id.news_content_keywords);

        listView = (MyListView) findViewById(R.id.news_content_listview);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.news_back_btn:
                    Intent intent = getIntent();
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
                case R.id.news_favorite_btn:
                    if (isLogin) {
                        if (TextUtils.isEmpty(titleStr)) {
                            Toast.makeText(NewsContentActivity.this, "数据正在加载中……", Toast.LENGTH_SHORT).show();
                        } else {
                            access_token = sharedPreferences.getString("access_token", "");
                            VolleyUtil.initFavorite(NewsContentActivity.this, id, TYPE, access_token, titleStr);
                        }
                    } else {
                        Toast.makeText(NewsContentActivity.this, "请先登录！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.news_share_btn:
                    Toast.makeText(NewsContentActivity.this, "share", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public void getData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        if (!FileUtil.fileIsExist(name)) {
            StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    FileUtil.saveFile(s, name);
                    initData(s);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            queue.add(request);
        } else {
            String s = FileUtil.readFile(name);
            initData(s);
        }
    }

    private void initData(String s) {
        News news = FileUtil.json4News(s);
        titleStr = news.getTitle();
        title.setText(titleStr);
        time.setText(news.getTime());
        from.setText("来源：掌上问医新闻");
        message.setText("\t\t" + news.getMessage());
        keywords.setText("关键字：" + news.getKeywords());
        initListView(news.getKeywords().trim());
    }

    private void initListView(String keywords) {
        String strUTF8 = null;
        try {
            strUTF8 = URLEncoder.encode(keywords, "utf-8");
            Log.e("==================", "encode utf:" + strUTF8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String address = "http://www.tngou.net/api/search?name=info&keyword=" + strUTF8 + "&rows=4";
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(Request.Method.GET, address, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                List<News> list = FileUtil.json4NewsItem(s);
                adapter = new NewsRelateListAdapter(NewsContentActivity.this, list);
                listView.setAdapter(adapter);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        int newsId = (int) (view.findViewById(R.id.news_relate_lv_txt)).getTag();
                        Intent intent = new Intent(NewsContentActivity.this, NewsContentRelateActivity.class);
                        intent.putExtra("id", newsId);
                        startActivityForResult(intent, 0);
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        queue.add(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }

}
